//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    canvasWidth: app.globalData.windowWidth * 0.8,
    canvasHeight: 400,
    userInfo: '',
    show: true,
    value: '显示',
    content: '我们来自五湖四海我们都是炎黄子孙中国举办了送'
  },
  showCanvas () {
    if(this.data.show){
      this.setData({
        value: '隐藏'
      })
      let marginLeft = this.calWidth(30), // 默认为rpx canvasWidth也为rpx
        liheight = 30
      console.log(marginLeft,liheight)
      let ctx = wx.createCanvasContext('mycas')
      // 背景
      // setInterval(()=>{
      ctx.setFillStyle('#ccc')
      ctx.fillRect(0, 0, this.data.canvasWidth, this.data.canvasHeight)
      // 头部文字

      ctx.setFillStyle('#000')
      ctx.setFontSize(15)
      //文字的长度
      let lineWidth = 0,
        lastIndex = 0,
        inY = 20,
        num = 0
      for (var i = 0; i < this.data.content.length; i++) {
        lineWidth += ctx.measureText(this.data.content[i]).width
        // 保证文本在中间
        if(lineWidth > (this.data.canvasWidth - marginLeft * 2 ) ) {
          // 把小于此长度的文字绘制出来（一次渲染）
          ctx.fillText(this.data.content.substring(lastIndex, i), marginLeft, (num++) * inY + liheight)
          console.log(this.data.content.substring(lastIndex, i))
          console.log(lastIndex,i,lineWidth)
          lastIndex = i
          lineWidth = ctx.measureText(this.data.content[i]).width

          console.log(1)
        }
        // 最多只2排
        if(num == 1){
            if(lineWidth + ctx.measureText('...').width > (this.data.canvasWidth - marginLeft * 2) / 2 ){
              ctx.fillText(this.data.content.substring(lastIndex, i) + '...', marginLeft, (num++) * inY + liheight)
              break
            }
        }
        //
        if( i == this.data.content.length -1) {
          ctx.fillText(this.data.content.substring(lastIndex, this.data.content.length ), marginLeft, num * inY + liheight)
          console.log(3)
          break
        }
      }
      ctx.save()
          // ctx.drawImage(this.data.userInfo.avatarUrl, 0, 0, 100, 100)
      ctx.restore()
      ctx.draw()

      // },1000)
      /*-------*/
    }else {
      this.setData({
        value: '显示'
      })
    }
    this.setData({
      show:!this.data.show
    })

  },
  calWidth (width) {
      return app.globalData.windowWidth / 750 * width
  },
  onLoad: function () {
  },
  getUserInfo(res) {
    console.log(res)
    let userInfo = {
      nickName:  res.detail.userInfo.nickName,
      avatarUrl: res.detail.userInfo.avatarUrl
    }
    this.setData({userInfo})
  }

})
